const fs = require('fs')
const path = require('path')
const program = require('commander')
const mkdirp = require('mkdirp')
const rimraf = require('rimraf')
const ora = require('ora')
const inquirer = require('inquirer')
const superagent = require('superagent')
const { resolve, prefix, getToken, isPc,deleteAll } = require('./utils')

const fetchSpinner = ora('获取模板中...')

module.exports = async () => {
  const token = getToken()
  if (!token) return

  const configPath = resolve('src/service/config.js')
  let themeId

  var isConfig=true
  try {
    themeId = require(configPath).themeId
    console.log('当前模板Id:'+ themeId)
  } catch (err) {
    isConfig=false
    console.info('不存在src/service/config，从服务器上请求模板')
    const themeRes = await superagent
      .post('/Site5ug/UserThemes', {
        ...token
      })
      .use(prefix)

    const {
      result: themeResult,
      status: thenmeStatus
    } = themeRes.body

    if (thenmeStatus !== 1) {
      console.error('模板列表获取失败')
      return
    }

    const { selectedId } = await inquirer
      .prompt({
        type: 'list',
        name: 'selectedId',
        message: '请选择模板',
        choices: themeResult.map(item => {
          return {
            name: item.name,
            value: item.key
          }
        })
      })

    themeId = selectedId
  }

  fetchSpinner.start()
  const initRes = await superagent
    .post('/GitFile/InitByThemeId', {
      loginInput: token,
      isConfig:isConfig,
      themeId
    })
    .use(prefix)
  fetchSpinner.stop()

  const {
    result: initResult,
    status: initStatus
  } = initRes.body

  if (initStatus !== 1){
    console.error('模板获取失败', initRes.body)
    return
  }
var componentPath=resolve('src/components')
rimraf.sync(componentPath)

  await Promise.all(initResult.map(file => new Promise((res, rej) => {
    const filePath = resolve(file.path)
    const dirPath = path.dirname(filePath)
    const fileName = filePath.replace(`${dirPath}${path.sep}`, '')

    mkdirp(dirPath, function (err) {
      if (err && program.debug) {
        console.error(err)
        return
      }
      fs.writeFile(filePath, file.content, err => {
        if (err) {
          rej(err)
          if (program.debug) console.error(err)
          console.log(`文件 ${fileName} 创建失败，路径 ${filePath}`)
          return
        }
        res()
        console.log(`文件 ${fileName} 创建成功，路径 ${filePath}`)
      })
    })
  })))
  await Promise.all([
    require('./icon')()
  ])

  await Promise.all([
    require('./main')()
  ])
  console.info('项目初始化成功,请运行项目')
}
